const db = uniCloud.database();
const flag = {}
import { userChapterList } from '@/common/api/list.js';
/**
 * 获取初始数据
 */
export async function getUserChapterList() {
	if (flag.chapter) return dzdata.userChapterList;
	flag.chapter = true;
	const { data } = await userChapterList();
	dzdata.userChapterList = data;
	setTimeout(() => {
		flag.chapter = false;
	}, 100)
}
/**
 * 根据课程id获取课程详情
 * @param {string} courseId 课程id
 */
export async function courseDetail({ courseId } = {}) {
	const collection_course = db.collection('a-dz-course-list');
	const collection_course_custom = db.collection('a-dz-course-list-custom');
	courseId = +courseId;
	const [courseData, nextCourseData, courseDataCustom, nextCourseDataCustom] = await Promise.all([
		collection_course.where({ courseId }).get(),
		collection_course.where({ courseId: db.command.gt(courseId) }).get({ getOne: true }),
		collection_course_custom.where({ courseId }).get(),
		collection_course_custom.where({ courseId: db.command.gt(courseId) }).get({ getOne: true })
	])
	const courseList = courseData.result.data.concat(courseDataCustom.result.data);
	const item = courseList[0];
	let nextItem = nextCourseData.result.data || nextCourseDataCustom.result.data;
	nextItem = nextItem ? nextItem : {};
	if (item?.category !== nextItem?.category) nextItem = null;
	item.nextCourse = nextItem;
	// console.log('item===>',item)
	return item;
}
/**
 * 通过uid获取当前用户的角色列表
 */
export async function getUserCharacterList() {
	const { uid = '' } = uniCloud.getCurrentUserInfo();
	if (!uid) return [];
	const { result } = await db.collection('a-dz-character-list').where(`uid == "${uid}"`).get();
	const characterList = result.data.map(item => {
		return {
			nickname: item.nickname,
			avatar: item.avatar,
			type: item.type,
			characterId: item.characterId
		}
	});
	return characterList;
}
/**
 * 根据角色ID获取该章节的完成度
 * @param {Object} options.characterId 角色id
 */
export async function getCategoryComplete(options = {}) {
	const characterId = getApp().globalData.dzcharacter?.character?.characterId;
	const { chapter } = options;
	const { uid } = uniCloud.getCurrentUserInfo();
	if (!uid) {
		throw new Error('非法请求');
	}
	if (!characterId || !chapter) {
		throw new Error('缺少characterId或chapter参数');
	}
	const dbCmd = db.command;
	const $ = db.command.aggregate;
	let categoryList = [];
	const [categoryListResult, categoryListCustomResult] = await Promise.all([
		db.collection('a-dz-category-list').aggregate().match({
			chapter: chapter
		}).lookup({
			from: 'a-dz-course-list',
			let: {
				mainid: '$category'
			},
			pipeline: $.pipeline().match(dbCmd.expr($.and([
				$.eq(['$category', '$$mainid']),
			]))).done(),
			as: 'courseList'
		}).lookup({
			from: 'a-dz-complete-list',
			let: {
				mainid: '$category'
			},
			pipeline: $.pipeline().match(dbCmd.expr($.and([
				$.eq(['$category', '$$mainid']),
				$.eq(['$characterId', characterId])
			]))).done(),
			as: 'completeList'
		}).project({
			name: 1,
			chapter: 1,
			category: 1,
			completedCourses: $.size('$completeList'),
			totalCourses: $.size('$courseList')
		}).end(),
		db.collection('a-dz-category-list-custom').aggregate().match({
			chapter: chapter
		}).lookup({
			from: 'a-dz-course-list-custom',
			let: {
				mainid: '$category'
			},
			pipeline: $.pipeline().match(dbCmd.expr($.and([
				$.eq(['$category', '$$mainid']),
			]))).done(),
			as: 'courseList'
		}).lookup({
			from: 'a-dz-complete-list-custom',
			let: {
				mainid: '$category'
			},
			pipeline: $.pipeline().match(dbCmd.expr($.and([
				$.eq(['$category', '$$mainid']),
				$.eq(['$characterId', characterId])
			]))).done(),
			as: 'completeList'
		}).project({
			name: 1,
			chapter: 1,
			category: 1,
			completedCourses: $.size('$completeList'),
			totalCourses: $.size('$courseList')
		}).end()
	])
	categoryList = categoryListResult.result.data.concat(categoryListCustomResult.result.data);
	return categoryList;
}
/**
 * 获取课程的完成度
 * @param {Object} options.characterId 角色id
 * @param {Object} options.category 课程类型
 */
export async function getCourseComplete(options = {}) {
	const characterId = getApp().globalData.dzcharacter?.character?.characterId;
	const { category } = options;
	const { uid } = uniCloud.getCurrentUserInfo();
	let courseList = [];
	if (!uid) {
		throw new Error('非法请求');
	}
	if (!characterId || !category) {
		throw new Error('缺少characterId或category参数');
	}
	const courseTemp = db.collection('a-dz-course-list').where(`category == "${category}"`).orderBy('courseOrder asc').limit(1000).getTemp();
	const courseTempCustom = db.collection('a-dz-course-list-custom').where(`category == "${category}" && uid == "${uid}"`).orderBy('courseOrder asc').limit(1000).getTemp();
	const completeTemp = db.collection('a-dz-complete-list').where(`category == "${category}" && characterId == "${characterId}"`).getTemp();
	const completeTempCustom = db.collection('a-dz-complete-list-custom').where(`category == "${category}" && characterId == "${characterId}"`).getTemp();
	const [courseListResult, courseListCustomResult] = await Promise.all([
		db.collection(courseTemp, completeTemp).get(),
		db.collection(courseTempCustom, completeTempCustom).get()
	]);
	courseList = courseListResult.result.data.concat(courseListCustomResult.result.data);
	courseList = courseList.map(item => {
		const complete = item.courseId['a-dz-complete-list'] || item.courseId['a-dz-complete-list-custom'];
		return {
			category: item.category,
			chapter: item.chapter,
			courseGroup: item.courseGroup,
			courseGroupName: item.courseGroupName,
			courseText: item.courseText,
			courseType: item.courseType,
			courseId: item.courseId._value,
			icon: item.icon,
			language: item.language,
			name: item.name,
			subscriptionType: item.subscriptionType,
			category: item.category,
			completeResult: complete.length ? complete[0] : null
		}
	})
	return courseList;
}
/**
 * 获取最后选中课程
 * @param {Object} options.characterId 角色id
 */
export async function getCourseLastActive() {
	const characterId = getApp().globalData.dzcharacter?.character?.characterId;
	if (!characterId) {
		throw new Error('缺少characterId参数');
	}
	const { result } = await db.collection('a-dz-active-list').where(`characterId == "${characterId}"`).get();
	const item = result.data[0]?.dzItem;
	setdzdata('lastActive', item);
	return item;
}
/**
 * 设置
 * @param {Object} value
 */
export function setdzdata(key, value) {
	dzdata[key] = value;
}
import { reactive } from 'vue';
export const dzdata = reactive({});